import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { MAINHOST } from '@/config';
import { Toast } from 'vant';
import  store  from '@/store/index';
import router from '@/router';

type Methods = "GET" | "POST" | "PUT" | "DELETE";
interface Datas { method?: Methods;[key: string]: any; };
const baseURL = process.env.NODE_ENV === 'production' ? MAINHOST : location.origin;

class HttpRequest {
  public queue: any // 请求的url集合
  public constructor() {
    this.queue = {}
  }
  destroy(url: string) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) { /*hide loading*/ }
  }
  interceptors(instance: any, url?: string) {
    // 请求拦截
    instance.interceptors.request.use((config: AxiosRequestConfig) => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) { /*show loading*/ }
      if (url) { this.queue[url] = true }
      return config
    }, (error: any) => {
      console.error(error);
    })
    // 响应拦截
    instance.interceptors.response.use((res: AxiosResponse) => {
      if (url) { this.destroy(url) }
      const { data, status } = res
      if (status === 200 && data && data.success) { return data.dataList } // 请求成功
      return requestFail(status, data.reason) // 失败回调
    }, (error: any) => {
      if (url) { this.destroy(url) }
      return requestFail(error.response.status, error.response.reason) ;
    })
  }
  // 注册异步方法
  async request(options: AxiosRequestConfig) {
    const instance = axios.create()
    await this.interceptors(instance, options.url)
    return instance(options)
  }
}

// 请求失败
const requestFail = (code: number, reason: any) => {
  if(code === 401) return store.commit('exit');
  Toast(reason);
  return Promise.reject({ code, reason });
}

// 合并axios参数
const conbineOptions = (method: Methods, url: string, data?: any): AxiosRequestConfig => {
  let headers = {};
  if (store.state.userInfo.token) {
    headers = { 'X-Access-Token': store.state.userInfo.token };
  }
  let options = {
    method, url, headers, 
    // baseURL,
    params: null, data: null
  };
  let query = null, body = null;
  if (data) {
    if (method == 'GET' || method == 'DELETE') { options.params = { ...data, _: new Date().getTime() } }
    else { options.data = data }
    if (data && data.query && data.query instanceof Object) { options.params = { ...data.query, _: new Date().getTime() } };
    if (data && data.body && data.body instanceof Object) { options.data = data.body };
  }
  return options
}

const HTTP = new HttpRequest()

/**
 * 抛出整个项目的api方法
 */
const Api = (() => {
  const apiObj: any = {};
  const requestMethods: any = { get: 'GET', delete: 'DELETE', post: 'POST', put: 'PUT' };
  const fun = (method: Methods) => {
    return async (url: string, data?: any) => {
      // 无token直接退出到登录页面
      // if (!token) { console.error('No Token'); return router.replace({ name: 'login' }); }
      const newOpts = conbineOptions(method, url, data)
      const res = await HTTP.request(newOpts)
      return res
    }
  }
  Object.keys(requestMethods).forEach((method) => {
    apiObj[method] = fun(requestMethods[method]);
  });

  return apiObj
})()

export default Api as any